package com.exercise.ThreadSynchronization.problem;

public class SafeCounterDemo {
    public static void main(String[] args) throws InterruptedException {
        SynchronizedCounter counter = new SynchronizedCounter();
        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 10000; i++) {
                counter.increment();
            }
        });
        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 10000; i++) {
                counter.increment();
            }
        });

        t1.start();
        t2.start();

        t1.join();
        t2.join();

        System.out.println("Final count: " + counter.getCount()); // 结果会是 20000
    }
}

class SynchronizedCounter {
    private int count = 0;

    //public synchronized void increment() { // 使用 synchronized 修饰方法
    //    count++;
    //}

    // 或者使用同步代码块
     public void increment() {
         synchronized (this) {
             count++;
         }
     }

    public int getCount() {
        return count;
    }
}
